package com.love_weinuo.ui;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;


import com.love_weinuo.R;
import com.love_weinuo.application.LoveApplication;
import com.love_weinuo.ui.activity.LoginActivity;
import com.love_weinuo.util.LogUtil;
import com.love_weinuo.util.dialog.InCommonDialog;
import com.love_weinuo.util.listener.OnBHClickListener;
import com.love_weinuo.util.rx.RxActivityTool;

import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.Stack;

/**
 * Created by Administrator
 * on 2019/2/20.
 */

public class BaseActivity extends AppCompatActivity implements View.OnClickListener {

    public static final String SYSTEM_EXIT = "com.bhxcw.Android";
    private Stack<WeakReference<Activity>> mActivityStack;
    ReceiveBroadCast receiveBroadCast;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //锁定竖屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }

        setNavWhiteColor();
        initBroadcast();
    }

    public void add(Activity activity) {
        RxActivityTool.addActivity(activity);
    }

    void initBroadcast() {
        receiveBroadCast = new ReceiveBroadCast();
        IntentFilter filter = new IntentFilter();
        filter.addAction("module_base");
        registerReceiver(receiveBroadCast, filter);
    }

    //标题栏返回调用方法
    public void setBack() {
        findViewById(R.id.topBarRelative).setVisibility(View.VISIBLE);
        findViewById(R.id.leftTitleText).setVisibility(View.GONE);
        findViewById(R.id.topBarRelative).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    //弹窗
    public void showInCommonDialog(final Context context, String str) {
        if (TextUtils.isEmpty(str)) {
            str = "未登录，请先登录";
        }
        InCommonDialog dialog = new InCommonDialog(this);
        dialog.setTitleText(str);
        dialog.show();
        dialog.setOnBHClickListener(new OnBHClickListener() {
            @Override
            public void onConfirmClick() {
                context.startActivity(new Intent(context.getApplicationContext(), LoginActivity.class));
            }

            @Override
            public void onCloseClick() {

            }
        });
    }

    public void showInCommonDialog(String string) {
        InCommonDialog dialog = new InCommonDialog(this);
        dialog.setTitleText(string);
        dialog.show();
    }

    public void showInCommonDialog() {
        InCommonDialog dialog = new InCommonDialog(this);
        dialog.setTitleText("未登录，请先登录");
        dialog.show();
        dialog.setOnBHClickListener(new OnBHClickListener() {
            @Override
            public void onConfirmClick() {
                LoveApplication.getInstance().startActivity(new Intent(LoveApplication.getInstance(), LoginActivity.class));
        }

            @Override
            public void onCloseClick() {

            }
        });
    }

    //设置标题栏中心标题
    public void setTitleText(String str) {
        try {
            TextView text = findViewById(R.id.bar_title);
            text.setText(str);
        } catch (Exception e) {
            LogUtil.e("标题栏设置有误");
        }
    }

    //设置标题栏右侧字体（如果是文字）
    public void setRightText(String str) {
        TextView text = findViewById(R.id.rightText);
        text.setText(str);
        text.setOnClickListener(this);
    }

    //设置标题栏右侧字体颜色（如果是文字）
    public void setRightTextColor(int id) {
        TextView text = findViewById(R.id.rightText);
        text.setTextColor(this.getResources().getColor(id));
    }

    //设置标题栏右侧图片
    public void setRightImg(int id) {
        ImageView image = findViewById(R.id.rightImage);
        image.setImageResource(id);
        image.setOnClickListener(this);
    }

    //设置标题栏左侧字体（如果是文字）
    public void setLeftText(String str) {
        findViewById(R.id.topBarRelative).setVisibility(View.VISIBLE);
        findViewById(R.id.left_icon).setVisibility(View.GONE);
        TextView text = findViewById(R.id.leftTitleText);
        text.setText(str);
        text.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

    }

    /**
     * 设置状态栏白底黑字
     */
    public void setNavWhiteColor() {
        //状态栏中的文字颜色和图标颜色，需要android系统6.0以上，而且目前只有一种可以修改（一种是深色，一种是浅色即白色）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //修改为深色，因为我们把状态栏的背景色修改为主题色白色，默认的文字及图标颜色为白色，导致看不到了。
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        //        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        //            Window window = getWindow();
        //            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        //            window.setStatusBarColor(ContextCompat.getColor(getApplicationContext(), R.color.black_six_one_half));
        //            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        //        }
    }

    private ProgressDialog mProgressDialog;

    public void showProgressDialog() {
        this.showProgressDialog("数据获取中", true);
    }

    public void showProgressDialog(String msg, boolean cancelable) {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setCancelable(cancelable);
        }
        if (TextUtils.isEmpty(msg)) {
            msg = "正在加载数据...";
        }
        mProgressDialog.setMessage(msg);
        mProgressDialog.show();
    }

    /**
     * 取消加载dialog
     */
    public void cancelProgressDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.cancel();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }

        if (receiveBroadCast != null) {
            unregisterReceiver(receiveBroadCast);
        }
    }

    /**
     * 添加Activity到栈
     *
     * @param activity
     */
    public void addActivity(Activity activity) {
        if (mActivityStack == null) {
            mActivityStack = new Stack<>();
        }
        mActivityStack.add(new WeakReference<>(activity));
    }

    /**
     * 检查弱引用是否释放，若释放，则从栈中清理掉该元素
     */
    public void checkWeakReference() {
        if (mActivityStack != null) {
            // 使用迭代器进行安全删除
            for (Iterator<WeakReference<Activity>> it = mActivityStack.iterator(); it.hasNext(); ) {
                WeakReference<Activity> activityReference = it.next();
                Activity temp = activityReference.get();
                if (temp == null) {
                    it.remove();
                }
            }
        }
    }

    /**
     * 获取当前Activity（栈中最后一个压入的）
     *
     * @return
     */
    public Activity currentActivity() {
        checkWeakReference();
        if (mActivityStack != null && !mActivityStack.isEmpty()) {
            return mActivityStack.lastElement().get();
        }
        return null;
    }

    /**
     * 关闭当前Activity（栈中最后一个压入的）
     */
    public void finishActivity() {
        Activity activity = currentActivity();
        if (activity != null) {
            finishActivity(activity);
        }
    }

    /**
     * 关闭指定的Activity
     *
     * @param activity
     */
    public void finishActivity(Activity activity) {
        if (activity != null && mActivityStack != null) {
            // 使用迭代器进行安全删除
            for (Iterator<WeakReference<Activity>> it = mActivityStack.iterator(); it.hasNext(); ) {
                WeakReference<Activity> activityReference = it.next();
                Activity temp = activityReference.get();
                // 清理掉已经释放的activity
                if (temp == null) {
                    it.remove();
                    continue;
                }
                if (temp == activity) {
                    it.remove();
                }
            }
            activity.finish();
        }
    }

    /**
     * 关闭指定类名的所有Activity
     *
     * @param cls
     */
    public void finishActivity(Class<?> cls) {
        if (mActivityStack != null) {
            // 使用迭代器进行安全删除
            for (Iterator<WeakReference<Activity>> it = mActivityStack.iterator(); it.hasNext(); ) {
                WeakReference<Activity> activityReference = it.next();
                Activity activity = activityReference.get();
                // 清理掉已经释放的activity
                if (activity == null) {
                    it.remove();
                    continue;
                }
                if (activity.getClass().equals(cls)) {
                    it.remove();
                    activity.finish();
                }
            }
        }
    }

    /**
     * 结束所有Activity
     */
    public void finishAllActivity() {
        if (mActivityStack != null) {
            for (WeakReference<Activity> activityReference : mActivityStack) {
                Activity activity = activityReference.get();
                if (activity != null) {
                    activity.finish();
                }
            }
            mActivityStack.clear();
        }
    }

    /**
     * 声明接收扫描结果的广播，
     */
    class ReceiveBroadCast extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //            if ("module_base".equals(intent.getAction())) {
            //                if (!TextUtils.isEmpty(intent.getStringExtra("module_broadcast_apk"))) {
            //                    LogUtil.e("apk下载地址："+ intent.getStringExtra("module_broadcast_apk"));
            //                    downApk(intent.getStringExtra("module_broadcast_apk"));
            //                }
            //
            //                if (!TextUtils.isEmpty(intent.getStringExtra("module_finish"))) {
            //                    LogUtil.e("关闭activity之广播："+ intent.getStringExtra("module_finish"));
            //                    if ("module_finish".equals(intent.getStringExtra("module_finish"))) {
            //                        finish();
            //                    }
            //                }
            //            }
        }
    }

    //apk更新下载
    //    public void downApk(String url){
    //        final String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/download";
    //        final String fileName = "bhyx.apk";
    //        File file = new File(filePath + "/" + fileName);
    //        if (file.exists())
    //            file.delete();
    //        showProgressDialog();
    //        OkGo.<File>get(url).tag(context).execute(new FileCallback(filePath,fileName) {
    //            @Override
    //            public void onSuccess(File file, Call call, Response response) {
    //                LogUtil.e("下载完成");
    //                ApkUtil.InstallAPK(BaseActivity.this,file.getAbsolutePath());
    //            }
    //
    //            @Override
    //            public void downloadProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
    //                //                LogUtil.e("下载进度 progress==>" + progress);
    //            }
    //        });
    //    }

}
